#ifndef CONNECTIONDIALOG_H
#define CONNECTIONDIALOG_H

#include <QApplication>
#include <QWidget>
#include <QLineEdit>
#include <QPushButton>
#include <QVBoxLayout>
#include <QDialog>
#include <QLabel>
#include <QTcpSocket>


class ConnectionDialog : public QDialog
{
    Q_OBJECT

public:
    ConnectionDialog(QWidget *parent = nullptr);
    ~ConnectionDialog();

    typedef enum {
        noerror,
        error,
        busy,
        nofile,
        nosupport,
        continue_enum,
        continue_read,
        read_done,
    }process_error_t;

    typedef enum {
        write,
        read,
        delete_file,
        enum_file,
        end,
    }command_t;


    typedef struct {
        char filename[32];
        char data[512];
    }write_cmd_t;

    typedef struct {
        char filename[32];
    }delete_cmd_t;

    typedef struct {
        int start;
        int size;
        char filename[32];
    }read_cmd_t;

    typedef union {
        write_cmd_t write_cmd;
        delete_cmd_t delete_cmd;
        read_cmd_t  read_cmd;
    }cmd_type_t;

    typedef struct {
        int command;
        int packet_id;
        int data_size;
        cmd_type_t cmd;
    }cmd_t;

    typedef struct {
        char filename[32];
    }write_ack_t;

    typedef struct {
        int file_num;
        char data[512];
    }enum_file_ack_t;

    typedef struct {
        int read_size; //实际读到的字节数
        int file_size;  //文件总大小
        char filename[32];
        char data[512];
    }read_ack_t;

    typedef union {
        write_ack_t write_ack;
        enum_file_ack_t enum_file_ack;
        read_ack_t read_ack;
    }ack_type_t;

    typedef struct {
        int cmd_ack;
        int packet_id;
        int flag;
        int data_size;
        ack_type_t ack;
    }ack_t;


signals:
    void setLogs(const QString &);

    void enum_down(QList<QString> list, int number);



public slots:
    void onConnectClicked();

    void onDisconnectClicked();

    void upload_slot(const QString &);

    void refresh_slot();

    void delete_cmd_slot(QString);

    void download_file_slot(QString);

private:
    QLineEdit *ipLineEdit;
    QLineEdit *portLineEdit;
    QPushButton *connectButton;
    QPushButton *disconnectButton;

    bool isValidIPv4(const QString &ip);

    void server_connect();

    void upload_thread(QString file);

    void refresh_server();

    void splitStringIntoList(QList<QString>& stringList, const char* charArray, int num);

    void delete_file_thread(QString file);

    void download_file_thread(QString file);


    // 添加一个成员变量来存储socket
    QTcpSocket* client_socket;
};
#endif // CONNECTIONDIALOG_H
